//
//  PEPackDataVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/8.
//

#import "RHLocalPackDataVC.h"
#import "RHCommonDataCell.h"
#import "RHDevEndPointDataModel.h"
#import "SYChartTool.h"
#import "CBLECenterMnger.h"
#import "RHLocalSettingModel.h"
#import "RHBleCmdManager.h"
#import "RHBleCmdData.h"
#import "CBLEDataParse.h"
#import "JCDataConvert.h"
@interface RHLocalPackDataVC ()
<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@end

@implementation RHLocalPackDataVC



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    
    [self readPackData];
}

-(void)readPackData
{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Local_Pack_data_cmd_noMaster"];//无主控
    if([CBLECenterMnger shareMnger].curPheral.hasMaster){
        arr = [SYChartTool loadJsonFileWithName:@"Local_Pack_data_cmd"];//有主控,Mtr_ubBatSt3401系统状态读的是master
    }

    //沛城16度电,没有正负极端口温度
    if ([CBLECenterMnger shareMnger].curPheral.productId == 300) {
        arr = [SYChartTool loadJsonFileWithName:@"Local_Pack_data_cmd_peicheng"];
    }
    
    self.cmdArray = [NSArray yy_modelArrayWithClass:[RHLocalSettingModel class] json:arr];
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.cmdType = [NSString stringWithFormat:@"%ld",101 + self.packIndex];
        //系统状态
        if([obj.field isEqualToString:@"Mtr_ubBatSt3401"]){
            obj.cmdType = [NSString stringWithFormat:@"%d",(int)LocalSettingType_Master];
        }
    }];
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
}

-(void)receiveDeviceMsg:(NSNotification *)no
{
    [super receiveDeviceMsg:no];
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
            
            NSData *data = dic[CMD_ADDRESS_VALUE];
            __block  NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
            NSLog(@"---->%@ = %@",obj.field,parse_content);
            
            if([obj.field isEqualToString:@"Pck_PACKSN"]){
                parse_content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            }
            //系统状态
            if(obj.isBit&&obj.selectList){
                [obj.selectList enumerateObjectsUsingBlock:^(RHLocalSettingOptionModel * _Nonnull optionModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if(optionModel.textValue == [parse_content integerValue]){
                        parse_content = optionModel.text.rh_localized;
                    }
                }];
            }
            
            if([obj.field isEqualToString:@"Pck_SwVerH"] && data.length == 2){
                NSData *softWare_H = [data subdataWithRange:NSMakeRange(0, 1)];
                NSInteger h_value = [JCDataConvert dataToInt:softWare_H];
                NSData *softWare_L = [data subdataWithRange:NSMakeRange(1, 1)];
                NSInteger l_value = [JCDataConvert dataToInt:softWare_L];
                parse_content = [NSString stringWithFormat:@"%ld.%03ld",h_value,l_value];
            }
            
            //系统时间  年(26-31)  月(22-25)  日(17-21)  时(12-16)  分(6-11)   秒(0-5)
            if([obj.field isEqualToString:@"Pck_SysTim1101"]){
                NSInteger yearOffsetValue = [CBLEDataParse offsetValueWithBitWidth:6];
                NSInteger year = ([parse_content integerValue] &(yearOffsetValue << 26))>>26;
                
                NSInteger monthOffsetValue = [CBLEDataParse offsetValueWithBitWidth:4];
                NSInteger month = ([parse_content integerValue] &(monthOffsetValue << 22))>>22;
                
                NSInteger dayOffsetValue = [CBLEDataParse offsetValueWithBitWidth:5];
                NSInteger day = ([parse_content integerValue] &(dayOffsetValue << 17))>>17;
                
                NSInteger hourOffsetValue = [CBLEDataParse offsetValueWithBitWidth:5];
                NSInteger hour = ([parse_content integerValue] &(hourOffsetValue << 12))>>12;
                
                NSInteger minuteOffsetValue = [CBLEDataParse offsetValueWithBitWidth:6];
                NSInteger minute = ([parse_content integerValue] &(minuteOffsetValue << 6))>>6;
                
                NSInteger secondOffsetValue = [CBLEDataParse offsetValueWithBitWidth:6];
                NSInteger second = ([parse_content integerValue] &secondOffsetValue)>>26;
                parse_content = [NSString stringWithFormat:@"20%02ld/%02ld/%02ld %02ld:%02ld:%02ld",year,month,day,hour,minute,second];
                if (year+month+day+hour+minute+second == 0) {
                    parse_content = @"--";
                }
                
            }
            
            
            [self.dataDic setObject:parse_content forKey:obj.field];
           
        }
    }];
    [self.tableView reloadData];
}

-(void)sendCmdFinish
{
    if(self.recieveMsg == NO)return;
    NSLog(@"----->读取到的信息:%@",self.dataDic);
    //压差
    if(self.dataDic[@"Pck_HV"] && self.dataDic[@"Pck_LV"]){
        NSInteger vol_dif = [self.dataDic[@"Pck_HV"] integerValue] - [self.dataDic[@"Pck_LV"] integerValue];
        NSString *volStr = [NSString stringWithFormat:@"%ld",vol_dif];
        [self.dataDic setObject:volStr forKey:@"Pck_HV_Dif"];
    }
    //温差
    if(self.dataDic[@"Pck_HT"]&&self.dataDic[@"Pck_LT"]){
        NSDecimalNumber *ht = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%lf",[self.dataDic[@"Pck_HT"] doubleValue]]];
        NSDecimalNumber *lt = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%lf",[self.dataDic[@"Pck_LT"] doubleValue]]];
        NSDecimalNumber *result = [ht decimalNumberBySubtracting:lt];
        [self.dataDic setObject:[NSString stringWithFormat:@"%@",result]  forKey:@"Pck_HT_Dif"];
    }
    
    //系统时间
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel*  _Nonnull sectionData, NSUInteger idx, BOOL * _Nonnull stop) {
        [sectionData.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel*  _Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if(self.dataDic[dataModel.keyCode]){
                dataModel.content = self.dataDic[dataModel.keyCode];
            }
        }];
    }];
    [self.tableView reloadData];
    [self.tableView endHeaderRefresh];
}

-(void)setupUI{
    
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    
    //数据源的key值有个别的跟命令的json文件key值不一样 (温差,压差,系统时间等)
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Local_Pack_data_noMaster"];
    if([CBLECenterMnger shareMnger].curPheral.hasMaster){
        arr = [SYChartTool loadJsonFileWithName:@"Local_Pack_data"];//有主控,Mtr_ubBatSt3401系统状态读的是master
    }
    
    //沛城16度电,没有正负极端口温度
    if ([CBLECenterMnger shareMnger].curPheral.productId == 300) {
        arr = [SYChartTool loadJsonFileWithName:@"Local_Pack_data_noMaster_peicheng"];
    }
    
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:arr];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonNormalCell];
   
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    _tableView.estimatedRowHeight = 180;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    //解决ios 12下移35的问题
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
    _tableView.tableFooterView = [UIView new];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf readPackData];
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}






#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    RHDevEndPointDataModel *eleModel = self.dataArr[section];
    return eleModel.infoArr.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    RHDevEndPointDataModel *eleModel = self.dataArr[section];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 50)];
    [headView addSubview:bgView];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.backgroundColor = [UIColor whiteColor];
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:eleModel.icon]];
    [bgView addSubview:icon];
    
    
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(14);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.numberOfLines = 0;
    titleLab.text = eleModel.title.rh_localized;
    [bgView addSubview:titleLab];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.right.mas_offset(-15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
   return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
    footer.backgroundColor = CFTabViewBgColor;
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, footer.width-30, 10)];
    subView.backgroundColor = [UIColor whiteColor];
    subView.layer.cornerRadius = 8;
    subView.layer.masksToBounds = YES;
    subView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [footer addSubview:subView];
    return footer;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHCommonDataCell *cell = [tableView dequeueReusableCellWithIdentifier:CommonNormalCell];
    RHDevEndPointDataModel *masterModel = self.dataArr[indexPath.section];
    cell.dataModel = masterModel.infoArr[indexPath.row];
    if(cell.dataModel.unit.length>0){
        cell.titleLab.text = [NSString stringWithFormat:@"%@(%@):",cell.dataModel.alias.rh_localized,cell.dataModel.unit];
    }
    return cell;

}



-(UIView *)listView
{
    return self.view;
}

@end
